package user03.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import user03.mapper.TUserRoleMapper;
import user03.model.TUserRole;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TUserRoleService extends ServiceImpl<TUserRoleMapper, TUserRole> {

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<Long> selectRoleIdsByUserId(Long userId) {
        List<Long> roleIds = new ArrayList<>();
        if (userId == null) {
            return roleIds;
        }
        QueryWrapper<TUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("t_user_id", userId);
        List<TUserRole> list = list(wrapper);
        if (list == null || list.size() <= 0) {
            return roleIds;
        }
        for (TUserRole tUserRole : list) {
            roleIds.add(tUserRole.getTRoleId());
        }
        return roleIds;
    }


    public Boolean updateUserRoles(Long userId, List<Long> roleIds) {
        Boolean delete = deleteByUserId(userId);
        if (delete != null && delete) {
            List<TUserRole> userRoles = new ArrayList<>();
            for (Long roleId : roleIds) {
                TUserRole userRole = new TUserRole();
                userRole.setTUserId(userId);
                userRole.setTRoleId(roleId);
                userRoles.add(userRole);
            }
            return saveBatch(userRoles);
        }
        return false;
    }

    public Boolean deleteByUserId(Long userId) {
        UpdateWrapper<TUserRole> wrapper = new UpdateWrapper<>();
        wrapper.eq("t_user_id", userId);
        return remove(wrapper);
    }

    public List<Long> selectUserIdsByRoleId(Long roleId) {
        List<Long> userIds = new ArrayList<>();
        if (roleId == null) {
            return userIds;
        }
        QueryWrapper<TUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("t_role_id", roleId);
        List<TUserRole> list = list(wrapper);
        if (list != null && list.size() > 0) {
            for (TUserRole userRole : list) {
                userIds.add(userRole.getTUserId());
            }
        }
        return userIds;
    }
}
